package com.ktg.mes.md.service.impl;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.google.gson.internal.LinkedTreeMap;
import com.ktg.common.core.domain.Result;
import com.ktg.common.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ktg.mes.md.mapper.MesScalesOrderItemMapper;
import com.ktg.mes.md.domain.MesScalesOrderItem;
import com.ktg.mes.md.service.IMesScalesOrderItemService;
import com.ktg.mes.md.mapper.MesScalesOrderMapper;
import com.ktg.mes.md.domain.MesScalesOrder;
import com.ktg.mes.md.service.IMesScalesOrderService;


/**
 * 销售订单Service业务层处理
 *
 * @author byteco
 * @date 2022-09-05
 */
@Service
public class MesScalesOrderServiceImpl extends ServiceImpl<MesScalesOrderMapper, MesScalesOrder> implements IMesScalesOrderService {
    @Autowired
    private MesScalesOrderMapper mesScalesOrderMapper;

    @Autowired
    private IMesScalesOrderItemService mesScalesOrderItemService;


    /**
     * 查询销售订单
     *
     * @param entity 销售订单
     * @param page   分页对象
     * @return 销售订单
     */
    @Override
    public IPage<MesScalesOrder> queryPageList(MesScalesOrder entity, Page<MesScalesOrder> page) {
        LambdaQueryWrapper<MesScalesOrder> lqw = buildQueryWrapper(entity);
        lqw.orderByDesc(MesScalesOrder::getCreateTime);
        IPage<MesScalesOrder> pageList = this.page(page, lqw);
        return pageList;
    }

    /**
     * 查询销售订单
     *
     * @param entity 销售订单
     * @return 销售订单
     */
    @Override
    public List<MesScalesOrder> queryList(MesScalesOrder entity) {
        LambdaQueryWrapper<MesScalesOrder> lqw = buildQueryWrapper(entity);
        lqw.orderByDesc(MesScalesOrder::getCreateTime);
        return this.list(lqw);
    }

    public MesScalesOrder getInfo(String id) {
        QueryWrapper<MesScalesOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MesScalesOrder::getScalesOrderId, id);
        return this.getOne(queryWrapper);
    }


    /**
     * 新增销售订单
     *
     * @param entity 销售订单
     * @return 结果
     */
    @Transactional
    @Override
    public void insert(MesScalesOrder entity) {
        entity.setCreateTime(DateUtils.getNowDate());
        if (entity.getRequestDate() == null) {
            entity.setRequestDate(new Date());
        }
        this.save(entity);
    }

    /**
     * 修改销售订单
     *
     * @param entity 销售订单
     * @return 结果
     */
    @Transactional
    @Override
    public boolean update(MesScalesOrder entity) {
        entity.setUpdateTime(DateUtils.getNowDate());
        return this.updateById(entity);
    }

    /**
     * 批量删除销售订单
     *
     * @param scalesOrderIds 需要删除的销售订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public boolean delete(String[] scalesOrderIds) {

        QueryWrapper<MesScalesOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("scales_order_id", Arrays.asList(scalesOrderIds));
        mesScalesOrderItemService.remove(queryWrapper);
        return this.removeByIds(Arrays.asList(scalesOrderIds));
    }

    /**
     * 删除销售订单信息
     *
     * @param scalesOrderId 销售订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public boolean delete(String scalesOrderId) {
        QueryWrapper<MesScalesOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("scales_order_id", Arrays.asList(scalesOrderId));
        mesScalesOrderItemService.remove(queryWrapper);
        return this.removeById(scalesOrderId);
    }

    @Override
    public void tpToEms(Map<String, Object> data) {
        MesScalesOrder mes = new MesScalesOrder();
        String code = (String) data.get("Code");
        QueryWrapper<MesScalesOrder> wrapper  = new QueryWrapper<>();
        wrapper.eq("scales_order_code",code);
        MesScalesOrder mesScalesOrder = mesScalesOrderMapper.selectOne(wrapper);
        mes.setScalesOrderCode((String) data.get("Code"));
        mes.setScalesOrderName("");
        Map customer = (LinkedTreeMap) data.get("Customer");
        if (customer != null) {
            mes.setClientId(((Double)customer.get("ID")).intValue() + "");
            mes.setClientCode((String) customer.get("Code"));
            mes.setClientName((String) customer.get("Name"));
        }
        mes.setRequestDate(DateUtils.parseDate(data.get("VoucherDate")));
        mes.setDeposit(new BigDecimal((String) data.getOrDefault("OrigEarnestMoney",0)));
        mes.setExplainDes((String)data.get("Memo"));
        Map clerk = (LinkedTreeMap)data.get("Clerk");
        if(clerk != null){
            mes.setSalesman((String)clerk.get("Name"));
        }
        mes.setRemark((String)data.get("Memo"));
        mes.setCreateBy((String)data.get("createBy"));
        mes.setCreateTime(DateUtils.parseDate(data.get("CreatedTime")));
        mes.setDataSource("TPLUS");
        if(mesScalesOrder != null){
            mes.setScalesOrderId(mesScalesOrder.getScalesOrderId());
            mesScalesOrderMapper.updateById(mes);
        }else{
            mes.setScalesOrderId(((Double)data.get("ID")).intValue() + "");
            mesScalesOrderMapper.insert(mes);
        }
        if(data.get("SaleOrderDetails") == null) return;
        ArrayList array = (ArrayList)data.get("SaleOrderDetails");
        List<MesScalesOrderItem> list = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            Map o = (LinkedTreeMap)array.get(i);
            Map inventory = (LinkedTreeMap)o.get("Inventory");
            if(inventory == null) break;
            MesScalesOrderItem item = new MesScalesOrderItem();
            item.setProductId(((Double)inventory.get("ID")).intValue() + "");
            item.setScalesOrderItemCode((String)inventory.getOrDefault("Code",""));
            item.setProductCode((String)inventory.getOrDefault("Code",""));
            item.setProductName((String)inventory.getOrDefault("Name",""));
            item.setProductSpc((String)inventory.getOrDefault("Specification",""));
            item.setViscosity((String)inventory.getOrDefault("priuserdefnvc1",""));
            item.setPackingType((String)inventory.get("priuserdefnvc3"));
            Map unit = (LinkedTreeMap)o.get("Unit");
            if(unit != null){
                item.setUnitOfMeasure((String)unit.get("Name"));
            }
            item.setQuantity(new BigDecimal((String)o.getOrDefault("Quantity","0")));
            item.setAmountMoney(new BigDecimal((String)o.getOrDefault("OrigTaxAmount","0")));
            item.setRequestDate(DateUtils.parseDate(data.get("VoucherDate")));
            item.setExplainDes((String)o.getOrDefault("DetailMemo",""));
            item.setClientId(((Double) customer.get("ID")).intValue() + "");
            item.setClientCode((String) customer.get("Code"));
            item.setClientName((String) customer.get("Name"));
            item.setCreateTime(DateUtils.parseDate(data.get("CreatedTime")));
            item.setCountSurplus(new BigDecimal((String)o.get("Quantity")));
            item.setScalesOrderId(mes.getScalesOrderId());
            item.setRemark((String)o.getOrDefault("DetailMemo",""));
            item.setTag((String)inventory.getOrDefault("priuserdefnvc2",""));
            QueryWrapper<MesScalesOrderItem> itemQw = new QueryWrapper<>();
            itemQw.eq("product_code",(String)inventory.getOrDefault("Code",""));
            MesScalesOrderItem mesScalesOrderItem = mesScalesOrderItemService.getBaseMapper().selectOne(itemQw);
            if(mesScalesOrderItem != null){
                item.setScalesOrderItemId(mesScalesOrderItem.getScalesOrderItemId());
            }else{
                item.setScalesOrderItemId(new BigDecimal((Double)inventory.get("ID")).longValue()+"");
            }
            list.add(item);
        }
        mesScalesOrderItemService.saveOrUpdateBatch(list);
    }

    private LambdaQueryWrapper<MesScalesOrder> buildQueryWrapper(MesScalesOrder entity) {
        LambdaQueryWrapper<MesScalesOrder> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(entity.getScalesOrderCode()), MesScalesOrder::getScalesOrderCode, entity.getScalesOrderCode());
        lqw.like(StringUtils.isNotBlank(entity.getScalesOrderName()), MesScalesOrder::getScalesOrderName, entity.getScalesOrderName());
        lqw.eq(StringUtils.isNotBlank(entity.getClientCode()), MesScalesOrder::getClientCode, entity.getClientCode());
        lqw.like(StringUtils.isNotBlank(entity.getClientName()), MesScalesOrder::getClientName, entity.getClientName());
        lqw.eq(StringUtils.isNotBlank(entity.getOrderStatus()), MesScalesOrder::getOrderStatus, entity.getOrderStatus());
        lqw.eq(StringUtils.isNotBlank(entity.getSalesman()), MesScalesOrder::getSalesman, entity.getSalesman());
        return lqw;
    }
}
